package com.lt.flashcard.view;

import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Page;
import org.zkoss.zk.ui.metainfo.ComponentInfo;
import org.zkoss.zk.ui.select.SelectorComposer;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zk.ui.util.Clients;
import org.zkoss.zul.Textbox;

import com.lt.flashcard.Utility;
import com.lt.flashcard.model.entity.User;
import com.lt.flashcard.model.service.AAService;
import com.lt.flashcard.model.service.EmailService;
import com.lt.flashcard.model.service.Repository;
import com.lt.flashcard.model.service.UserService;

public class ForgotPasswordCtrl extends SelectorComposer<Component> {

	private static final long serialVersionUID = 1L;

	@Wire
	private Textbox email;
	
	@Override
	public ComponentInfo doBeforeCompose(Page page, Component parent, ComponentInfo compInfo) {
		AAService srv  = Repository.getInstance().getAAService();
		if(srv.isLogin()) {
			Executions.sendRedirect("/wordlist.zul");
			return null;
		}
		return super.doBeforeCompose(page, parent, compInfo);
	}
	
	/*
	 * Do Login
	 */
	@Listen("onClick=#btnSendEmail; onOK=#email")
	public void doSend() {
		if(Utility.isEmptyString(email.getValue())) {
			Clients.evalJavaScript("showNotice('', 'Bạn chưa nhập email')");
			return;
		}
		UserService srv1 = Repository.getInstance().getUserService();
		try {
			User user = srv1.findUserByEmail(email.getValue());
			if(user != null && user.getBlock() == 0) {
				UUID idOne = UUID.randomUUID();
				user.setActivation(idOne.toString());
				Calendar cal = Calendar.getInstance();
				cal.setTime(new Date());
				cal.add(Calendar.DATE, 30);
				user.setExpiredate(cal.getTime());//expire date
				srv1.save(user);
				
				//do send email
				EmailService esrv = Repository.getInstance().getEmailService();
				esrv.sendEmailResetPassword(user.getUsername(), user.getEmail(), user.getActivation());
			}
			else if(user.getBlock() == 1) {
				Clients.evalJavaScript("showNotice('', 'Tài khoản này đã bị khóa. Hãy liên lạc với admin!')");
				return;
			}
		} catch(Exception e) { }
		
		Clients.evalJavaScript("showNotice('', 'Email đã được gửi. Vui lòng check mail')");
	}
	
	public Textbox getEmail() {
		return email;
	}
	
	public void setEmail(Textbox email) {
		this.email = email;
	}
}
